package com.gzcstec.gateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.gzcstec.gateway.enums.ExceptionEnums;
import com.gzcstec.gateway.exception.RateLimiterException;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SERVLET_DETECTION_FILTER_ORDER;

/**
 * 限流过滤
 */
@Component
public class RateLimiterFilter extends ZuulFilter {

    /*定义token每秒创建个数*/
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    /**
     * 数据越小，优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return SERVLET_DETECTION_FILTER_ORDER -1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //判断是否获得token
        if(!RATE_LIMITER.tryAcquire()) {
            //剖出异常
            throw new RateLimiterException(ExceptionEnums.RATE_LIMITER_EXCEPTION);
        }
        return null;
    }
}
